package My.project.Util;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import My.project.Entity.People;
import My.project.Entity.User;
import My.project.Entity.Video;

/**
 * Connector class, responsible for the network connection.
 * @author Bell
 *
 */
public class Connector {

	//server ip, need to be refreshed
	public static String videoUrl = 
			"http://192.168.1.104/net/client/videoplayer.php?" +
			"source=%20rtmp://192.168.1.104";
	public static String webServerUrl = "http://192.168.1.104/net/client/";
	
	/**
	 * Get all users.
	 * @return List<People> A list of People instances.
	 */
	public List<People> getPeopleList() {
		String uriApi = webServerUrl + "showFriends.php";
		String strRet = "";
		
		try{
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = null;
			HttpPost httppost = new HttpPost(uriApi);
			List <NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("uid", User.getUid()));
			
			httppost.setEntity(
					new UrlEncodedFormEntity(nvps, HTTP.UTF_8));		
			response = httpclient.execute(httppost);
			if(response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				
				//html post response body
				strRet = EntityUtils.toString(entity);
				System.out.println("###############");
				System.out.println(strRet.substring(3));
				XmlParser parser = new XmlParser();
				
				return parser.parsePeople(strRet.substring(3));
			}
			return null;
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
		/*String tmp = "<users><user><uid>1</uid><nick>a</nick><des>is a</des>" +
				"<ifFriend>1</ifFriend></user><user><uid>1</uid><nick>b</nick>" +
				"<des>is a</des><ifFriend>0</ifFriend></user><user>" +
				"<uid>1</uid><nick>c</nick><des>is a</des>" +
				"<ifFriend>1</ifFriend></user></users>";
		XmlParser parser = new XmlParser();
		return parser.parsePeople(tmp);*/
	}
	
	/**
	 * Get all live video.
	 * @return List<Video> The list of Video type entity.
	 */
	public List<Video> getVideoList() {
		String uriApi = webServerUrl + "showVideoList.php";
		String strRet = "";
		
		try{
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = null;
			HttpPost httppost = new HttpPost(uriApi);
			
			response = httpclient.execute(httppost);
			if(response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				
				//html post response body
				strRet = EntityUtils.toString(entity);
				if(strRet.equals("<VideoList></VideoList>")) {
					List<Video> lv = new ArrayList<Video>();
					Video tmp = new Video("No Video", null, null);
					lv.add(tmp);
					return lv;
				}
				XmlParser parser = new XmlParser();
				
				return parser.parseVideo(strRet);
			}
			Video tmp = new Video("error", "can not connect to server", null);
			List<Video> lv = new ArrayList<Video>();
			lv.add(tmp);
			return lv;
		}
		catch(Exception e){
			e.printStackTrace();
			Video tmp = new Video("error", null, "unknown error");
			List<Video> lv = new ArrayList<Video>();
			lv.add(tmp);
			return lv;
		}
		/*String tmp = "<Videos><Video><VideoName>test</VideoName><Vid>0</Vid>" +
				"<VideoType>this is for test</VideoType><VideoDes>test</VideoDes>" +
				"<rtmp>test</rtmp></Video><Video><VideoName>test</VideoName><Vid>0</Vid>" +
				"<VideoType>this is for test</VideoType><VideoDes>test</VideoDes>" +
				"<rtmp>test</rtmp></Video><Video><VideoName>test</VideoName><Vid>0</Vid>" +
				"<VideoType>this is for test</VideoType><VideoDes>test</VideoDes>" +
				"<rtmp>test</rtmp></Video></Videos>";
		XmlParser parser = new XmlParser();
		return parser.parseVideo(tmp);*/
	}
	
	/**
	 * User log in function.
	 * @param username The username of the user.
	 * @param password The password of the user.
	 * @return String Result of log in.
	 */
	public String Login(String username, String password){
		//User.setUid("1");
		//return "Welcome!";
		String uriApi = webServerUrl + "login.php";
		String strRet = "";
		
		try{
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = null;
			HttpPost httppost = new HttpPost(uriApi);
			List <NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("username", username));
			nvps.add(new BasicNameValuePair("password", password));
			
			httppost.setEntity(
					new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			response = httpclient.execute(httppost);
			System.out.println(response.getStatusLine().getStatusCode());
			if(response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				
				//html post response body
				strRet = EntityUtils.toString(entity);
				
				System.out.println(strRet);
				if(strRet.contains("success")) {
					System.out.println("login success");
					int no = strRet.indexOf(" success");
					String uid = strRet.substring(0, no);
					User.setUid(uid);
					return "Welcome!";
				}
				else if (strRet.equals("failed")) {
					System.out.println("login failed");
					return "Login fail, please try again";
				}
			}
			return "Cannot connect to server, please try again";
		}
		catch(Exception e){
			e.printStackTrace();
			return "Unknown exception, please try again";
		}
	}
	
	/**
	 * Register function.
	 * @param name The user's log in name.
	 * @param nick The user's nickname.
	 * @param secret The user's password.
	 * @return String Result of register function.
	 */
	public String register(String name, String nick, String secret) {
		String uriApi = webServerUrl + "register.php";
		String strRet = "";
		
		try{
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = null;
			HttpPost httppost = new HttpPost(uriApi);
			List <NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("name", name));
			nvps.add(new BasicNameValuePair("nick", nick));
			nvps.add(new BasicNameValuePair("secret", secret));
			
			httppost.setEntity(
					new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			response = httpclient.execute(httppost);
			//System.out.println("fuck!!!" + response.getStatusLine().getStatusCode());
			if(response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				
				/*html post response body*/
				strRet = EntityUtils.toString(entity);
				//System.out.println(strRet);
				if(strRet.contains("success")) {
					System.out.println("register success");
					return "Register succeed!";
				}
				else if (strRet.equals("fail")) {
					System.out.println("register failed");
					return "Register failed, please try again";
				}
			}
			return "Cannot connect to server, please try again";
		}
		catch(Exception e){
			e.printStackTrace();
			return "Unknown exception, please try again";
		}
	}
	
	/**
	 * Search Video according to a keyword.
	 * @param keyword The keyword of the search.
	 * @return List<Video> List of related videos.
	 */
	public List<Video> searchVideo(String keyword) {
		String uriApi = webServerUrl + "searchVideo.php";
		//String uriApi = "http://192.168.1.115/my/searchVideo.php";
		String strRet = "";
		
		try{
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = null;
			HttpPost httppost = new HttpPost(uriApi);
			List <NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("keyWord", keyword));
			httppost.setEntity(
					new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			response = httpclient.execute(httppost);
			if(response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				//html post response body
				strRet = EntityUtils.toString(entity);
				System.out.println(strRet);
				if(strRet.equals("there is no video")) {
					List<Video> lv = new ArrayList<Video>();
					Video tmp = new Video("No Video", null, null);
					lv.add(tmp);
					return lv;
				}
				XmlParser parser = new XmlParser();
				
				return parser.parseVideo(strRet);
			}
			return null;
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
		/*String tmp = "<Videos><Video><VideoName>test</VideoName><Vid>0</Vid>" +
				"<VideoType>this is for test</VideoType><VideoDes>test</VideoDes>" +
				"<rtmp>test</rtmp></Video><Video><VideoName>test</VideoName><Vid>0</Vid>" +
				"<VideoType>this is for test</VideoType><VideoDes>test</VideoDes>" +
				"<rtmp>test</rtmp></Video><Video><VideoName>test</VideoName><Vid>0</Vid>" +
				"<VideoType>this is for test</VideoType><VideoDes>test</VideoDes>" +
				"<rtmp>test</rtmp></Video></Videos>";
		XmlParser parser = new XmlParser();
		return parser.parseVideo(tmp);*/
	}
	
	/**
	 * Upload video to server.
	 * @param uploadFile The path of the video.
	 * @param fileName The name of the video.
	 * @param fileDes The description of the video.
	 * @return String Result from the server.
	 */
	public String upload(String uploadFile, String fileName, String fileDes) {
		String actionUrl = webServerUrl + "uploadVideo.php";
		//String actionUrl = "http://192.168.1.114/uploadFile.php";
		
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		
		try {
			System.out.println(uploadFile);
			URL url = new URL(actionUrl);
			HttpURLConnection con = 
					(HttpURLConnection)url.openConnection();
			con.setChunkedStreamingMode(128 * 1024);// 128K  
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			con.setRequestMethod("POST");
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			DataOutputStream ds = new DataOutputStream(
					con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			System.out.println("@@@@@@@@@@" + fileName);
			// TODO add fileDes
			ds.writeBytes("Content-Disposition: form-data;" +
					"name=\"uploadedfile\";filename=\"" + fileName + "\"" + end);
			/*ds.writeBytes("Content-Disposition: form-data;" +
					"name=\"file\";filename=\"" + fileName + "\";fileDes=\""
					+ fileDes + "\"" + end);*/
			ds.writeBytes(end);
			FileInputStream fStream = new FileInputStream(uploadFile);
			int buffersize = 8192;
			byte[] buffer = new byte[buffersize];
			int length = -1;
			while((length = fStream.read(buffer)) != -1){
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			
			fStream.close();
			ds.flush();
			
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while((ch = is.read()) != -1){
				b.append((char)ch);
			}
			//System.out.println(b.toString().trim());
			ds.close();
			is.close();
			return b.toString().trim();
		} catch(Exception e){
			e.printStackTrace();
		}
		return "error";
	}
}
